package com.shang.dao;

import com.shang.entity.Comment;
import com.shang.entity.Comment2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MongoChangeDao {

    @Autowired
    private MongoTemplate mongoTemplate;

    public List<Comment> getCommentListByPage(int pageNum,int pageSize){
        String collectionName="comment";
        if (pageNum!=0){
            pageNum--;
        }
        Pageable pageable = PageRequest.of(pageNum, pageSize);
        Query query=new Query().with(pageable);
        List<Comment> comments = mongoTemplate.find(query, Comment.class, collectionName);
        return comments;
    }
    public void insertComment2(Comment2 comment2){
        long commentId=getCurmax();
        comment2.setComment_id(commentId+1);
        mongoTemplate.insert(comment2,"comment2");
    }

    private long getCurmax() {
        String collectionName="comment2";
        Query query =new Query().with(Sort.by(Sort.Direction.DESC,"comment_id")).limit(1);
        Comment2 comment2 = mongoTemplate.findOne(query, Comment2.class, collectionName);
        return comment2.getComment_id();
    }
}
